using System;
using UnityEngine;

namespace Lean.Localization
{
	public class LeanLocalizationLoader : MonoBehaviour
	{
		[Tooltip("The LeanLocalization target the translations will be loaded into. If this is empty, the first in the scene will automatically be used. If there are none in the scene, one will be created")]
		public LeanLocalization Target;

		[Tooltip("The file with all the translations in")]
		public TextAsset Source;

		[Tooltip("The language of the translations in the source file")]
		[LeanLanguageName]
		public string SourceLanguage;

		[Tooltip("The string separating the phrase name from the translation")]
		public string Separator = " = ";

		[Tooltip("The string denoting a new line within a translation")]
		public string NewLine = "\\n";

		[Tooltip("The string separating the translation from the comment (empty = no comments)")]
		public string Comment = " // ";

		private static readonly char[] newlineCharacters = new char[2]
		{
			'\r',
			'\n'
		};

		protected virtual void Start()
		{
			LoadFromSource();
		}

		[ContextMenu("Load From Source")]
		public void LoadFromSource()
		{
			if (!(Source != null) || string.IsNullOrEmpty(SourceLanguage))
			{
				return;
			}
			LeanLocalization leanLocalization = Target;
			if (leanLocalization == null && LeanLocalization.AllLocalizations.Count > 0)
			{
				leanLocalization = LeanLocalization.AllLocalizations[0];
			}
			if (leanLocalization == null)
			{
				leanLocalization = new GameObject("LeanLocalization").AddComponent<LeanLocalization>();
			}
			string[] array = Source.text.Split(newlineCharacters, StringSplitOptions.RemoveEmptyEntries);
			foreach (string text in array)
			{
				int num = text.IndexOf(Separator);
				if (num == -1)
				{
					continue;
				}
				string phraseName = text.Substring(0, num).Trim();
				string text2 = text.Substring(num + Separator.Length).Trim();
				if (!string.IsNullOrEmpty(NewLine))
				{
					text2 = text2.Replace(NewLine, Environment.NewLine);
				}
				if (!string.IsNullOrEmpty(Comment))
				{
					int num2 = text2.LastIndexOf(Comment);
					if (num2 != -1)
					{
						text2 = text2.Substring(0, num2).Trim();
					}
				}
				LeanTranslation leanTranslation = leanLocalization.AddTranslation(SourceLanguage, phraseName);
				leanTranslation.Text = text2;
			}
			if (LeanLocalization.CurrentLanguage == SourceLanguage)
			{
				LeanLocalization.UpdateTranslations();
			}
		}
	}
}
